﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using HsTec.DigitalPlatform.Business;
using HsTec.DigitalPlatform.DataAccess;
using HsTec.DigitalPlatform.Model.DTO;

namespace HsTec.DigitalPlatform.WebSite.Controllers
{
    public class MainController : Controller
    {
        //
        // GET: /Main/
        MenuInfoManager menuinfomanager = new MenuInfoManager();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Welcome()
        {
            return View();
        }

        public JsonResult GetTreeRoot()
        {
            MenuInfo root = menuinfomanager.GetRoot();
            JsonTreeNode rootnode = new JsonTreeNode();
            rootnode.id = root.menuid.ToString();
            rootnode.text = root.menuname;
            rootnode.isexpand = true;

            List<MenuInfo> menuinfolist = menuinfomanager.FindChildMenuInfoByParentID(root.menuid).ToList<MenuInfo>();
            rootnode.ChildNodes = buildTreeNodeFromMenuInfo(menuinfolist, 0);
            rootnode.hasChildren = rootnode.ChildNodes != null && rootnode.ChildNodes.Count > 0;
            List<JsonTreeNode> list = new List<JsonTreeNode>();
            list.Add(rootnode);
            return Json(list);
        }

        //返回树形菜单
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult GetChildData(FormCollection form)
        {
            int id = Convert.ToInt32(form["id"]);
            List<MenuInfo> list = menuinfomanager.FindChildMenuInfoByParentID(id).ToList<MenuInfo>();
            return Json(buildTreeNodeFromMenuInfo(list, 0));
        }

        private List<JsonTreeNode> buildTreeNodeFromMenuInfo(List<MenuInfo> menuinfolist, byte state)
        {
            return menuinfolist.ConvertAll<JsonTreeNode>(x =>
            {
                return new JsonTreeNode()
                {
                    id = x.menuid.ToString(),
                    text = x.menuname,
                    value = x.menuurl,
                    isexpand = false,
                    checkstate = state,
                    hasChildren = x.haschild > 0 ? true : false
                };
            });

        }
    }
}
